/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package replacer;

import com.csvreader.CsvReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Miky
 */
public class Main {

    private static CsvReader readerMap;
    private static FileInputStream fis;
//    private static HashMap<String, String> map = new HashMap<>();
    private static ArrayList<String> czLetters = new ArrayList<>();
    private static ArrayList<String> badStrings = new ArrayList<>();
    private static String mapFile = "map.csv";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            fillMapBy(mapFile);
            initWindow();

//            if (args.length != 2) {
//                System.out.println("Usage:");
//                System.out.println("File with map.");
//                System.out.println("File with text.");
//                return;
//            }

//            String textFile = args[1];
//            String mapFile = args[0];

            //        proceed(textFile, mapFile, "OK_"+textFile);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void proceed(File textFile, String newFileName) {
        try {
//            System.out.println("czLetters.size(): " + czLetters.size());
//            System.out.println("badStrings.size(): " + badStrings.size());
            for (int i = 0; i < czLetters.size(); i++) {
//                System.out.println(czLetters.get(i) + ";" + badStrings.get(i));
            }
            readFile(textFile, newFileName);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void printArray(ArrayList<String> pole) {
        for (int i = 0; i < pole.size(); i++) {
            System.out.println(pole.get(i));
        }
    }

    private static void fillMapBy(String fileName) throws IOException {

        try {
            readerMap = new CsvReader(fileName, ';', Charset.forName("UTF-8"));

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        while (readerMap.readRecord()) {
            String czLetter = readerMap.get(0);
//            String badString = readerMap.get(1);

//            map.put(badString, czLetter);
//            czLetters.add(czLetter);
//            badStrings.add(badString);

//            String badString2 = "";
//            String badString3 = "";

            for (int i = 1; i < readerMap.getColumnCount(); i++) {
                czLetters.add(czLetter);
                badStrings.add(readerMap.get(i));
            }


//            if (readerMap.getColumnCount() >= 3) {
//                badString2 = readerMap.get(2);
//                czLetters.add(czLetter);
//                badStrings.add(badString2);
//            }
//            if (readerMap.getColumnCount() >= 4) {
//                badString3 = readerMap.get(3);
//                czLetters.add(czLetter);
//                badStrings.add(badString3);;
//            }
        }
    }

    private static void readFile(File file, String newFileName) throws IOException {
        try {

            FileInputStream fstream = new FileInputStream(file);
            // Get the object of DataInputStream
            DataInputStream dis = new DataInputStream(fstream);
            BufferedReader brIn = new BufferedReader(new InputStreamReader(dis));
            String strLine;

            // pro zapis
            File repair = new File(file.getParent() + "/repair/");
            repair.mkdir();
            FileWriter fileWritter = new FileWriter(new File(file.getParent() + "/repair/" + file.getName()), true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);

            //Read File Line By Line
            while ((strLine = brIn.readLine()) != null) {
                String replaced = strLine;
                
                for (int i = 0; i < badStrings.size(); i++) {
                    replaced = replaced.replace(badStrings.get(i), czLetters.get(i));
                }
                bufferWritter.write(replaced + System.getProperty("line.separator"));
            }
            //Close the input stream
            bufferWritter.close();
            dis.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

    }

    private static void initWindow() {
//        Frame window = new Frame();
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Okno().setVisible(true);
            }
        });
    }
}
